import 'reflect-metadata';
import { DataSource } from 'typeorm';
import { Session } from '../src/domain/entities/session.entity';
import { Message } from '../src/domain/entities/message.entity';
import { User } from '../src/domain/entities/user.entity';
import { ConfigService } from '../src/infrastructure/config/config.service';
import { createDataSource } from '../src/infrastructure/database/typeorm.config';

interface MockChat {
  id: string;
  title: string;
  preview: string;
  time: string;
  avatar?: string;
  highlighted?: boolean;
  isPrivate?: boolean;
  type?: string;
  isOnline?: boolean;
}

interface MockMessage {
  id: string;
  type: 'system' | 'user';
  sender: string;
  content: string;
  time: string;
  collapsible?: boolean;
  collapsed?: boolean;
}

const mockChatList: MockChat[] = [
  {
    id: '5f87c7d1-56a6-4c7a-8840-51f1b35e8f0d',
    title: 'd_17788952859',
    preview: '是的吗但是',
    time: '今天 15:49',
  },
  {
    id: '8c22e320-9e1a-42d6-9464-f4fe97e1b21c',
    title: 'lkun233的群组',
    preview: 'lkun233: 打杂***',
    time: '今天 15:48',
  },
  {
    id: 'c7452f9c-64bf-4a70-8a3e-a5c5ebf1c23b',
    title: '讯飞星火',
    preview: '"撕掰码洛伊" 是一种吵嘴的行为，...',
    time: '今天 15:48',
    isPrivate: true,
    type: 'ai-fire',
  },
];

const createMockMessages = (chatId: string, aiName: string): MockMessage[] => {
  const chatIdEnd = chatId.substring(chatId.length - 4);
  const messageCount = (parseInt(chatIdEnd, 16) % 3) + 1; // 1-3 条消息

  const baseMessages: MockMessage[] = [];

  baseMessages.push({
    id: `welcome-${chatId}`,
    type: 'system',
    sender: aiName,
    collapsible: true,
    collapsed: false,
    content: `欢迎使用聊天系统，这是对话 ${chatId.substring(0, 8)}。您可以开始输入消息进行交流。`,
    time: new Date(Date.now() - 1000 * 60 * 60 * 24 * 2).toISOString(),
  });

  for (let i = 0; i < messageCount; i++) {
    baseMessages.push({
      id: `user-${chatId}-${i}`,
      type: 'user',
      sender: 'lkun233',
      content: `这是测试消息 ${i + 1} 在对话 ${chatId.substring(0, 6)}`,
      time: new Date(Date.now() - 1000 * 60 * 60 * (messageCount - i)).toISOString(),
    });

    baseMessages.push({
      id: `ai-${chatId}-${i}`,
      type: 'system',
      sender: aiName,
      content: `这是第 ${i + 1} 条消息的回复。我是 ${aiName}，很高兴为您服务。`,
      time: new Date(Date.now() - 1000 * 60 * 60 * (messageCount - i) + 1000 * 60 * 2).toISOString(),
    });
  }

  return baseMessages;
};

const getAiNameForChat = (chatId: string): string => {
  const aiNames = ['DeepSeekV3', '星火认知大模型', 'GPT-4'];
  const index = parseInt(chatId.substring(0, 2), 16) % aiNames.length;
  return aiNames[index];
};

const mockChatMessages: { [chatId: string]: MockMessage[] } = {};
mockChatList.forEach(chat => {
  const aiName = getAiNameForChat(chat.id);
  mockChatMessages[chat.id] = createMockMessages(chat.id, aiName);
});

async function seedDatabase() {
  const configService = new ConfigService();
  const dataSource = createDataSource(configService);
  await dataSource.initialize();
  console.log('Database connected');

  const sessionRepo = dataSource.getRepository(Session);
  const messageRepo = dataSource.getRepository(Message);
  const userRepo = dataSource.getRepository(User);

  // 清空现有数据（可选，开发环境使用）
//   await messageRepo.delete({});
//   await sessionRepo.delete({});
//   await userRepo.delete({});

  // 插入测试用户
  const users = [
    { id: 'user-lkun233', username: 'lkun233', status: 'online' },
    { id: 'user-ai-agent', username: 'AI-Agent', status: 'online' },
  ];
  await userRepo.save(users);
  console.log('Inserted users:', users.length);

  // 插入会话和消息
  for (const chat of mockChatList) {
    const session = new Session();
    session.id = chat.id;
    session.participants = ['user-lkun233', 'user-ai-agent'];
    session.agentId = 'default-agent';
    session.createdAt = new Date();
    session.updatedAt = new Date();
    await sessionRepo.save(session);

    const messages = mockChatMessages[chat.id];
    for (const msg of messages) {
      const message = new Message();
      message.id = msg.id;
      message.sessionId = chat.id;
      message.senderId = msg.sender === 'lkun233' ? 'user-lkun233' : 'user-ai-agent';
      message.content = msg.content;
      message.timestamp = new Date(msg.time);
      await messageRepo.save(message);
    }
    console.log(`Inserted session ${chat.id} with ${messages.length} messages`);
  }

  await dataSource.destroy();
  console.log('Database seeding completed');
}

seedDatabase().catch(console.error);